Implementing if-elif-else Conditions in Python
Course: Python Programming
Topic: Implementing if-elif-else Conditions
Course Link: Python Training Course – JustAcademy
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to if-elif-else Conditions
Decision-making is an important part of programming. It allows a program to select different actions based on conditions. In Python, the if, elif, and else statements are used to control the flow of execution and make decisions.
The if-elif-else structure is especially useful when a program needs to choose one option from several possible alternatives. For example, it can classify a student's marks into grades, calculate a discount based on a purchase amount, determine a ticket price based on age, or display a message according to a user's choice.
The word elif means “else if.” It allows Python to test another condition when the previous condition is false.
1.1 Why Are Conditional Statements Needed?
- To execute different blocks of code based on different situations.
- To validate user input and check whether it meets specific requirements.
- To classify values into categories such as low, medium, and high.
- To implement business rules such as discounts, eligibility, and grading systems.
- To make programs interactive and responsive to changing input.
1.2 Example of Decision-Making
temperature = 35
if temperature > 40:
print("Very hot")
elif temperature > 30:
print("Hot weather")
elif temperature > 20:
print("Pleasant weather")
else:
print("Cool weather")
Output:
Hot weather
The first condition is false because 35 is not greater than 40. Python then checks the second condition, which is true. It prints Hot weather and skips the remaining branches.
2. Understanding the if Statement
The if statement checks a condition. If the condition evaluates to True, Python executes the indented block underneath it. If the condition evaluates to False, Python skips that block and continues with the next statement.
2.1 Syntax of if
if condition:
# Statements executed when the condition is True
statement
2.2 Example
age = 20
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
Because age >= 18 evaluates to True, Python executes the print statement.
2.3 Important Points
- The
if keyword must be followed by a condition.
- A colon (
:) is required at the end of the condition line.
- The statements inside the block must be indented.
- Python executes the block only when the condition is true.
3. Understanding the elif Statement
The elif statement adds another condition to an existing conditional structure. Python evaluates an elif condition only when the preceding if or elif conditions have all evaluated to false.
3.1 Syntax of elif
if first_condition:
statement_1
elif second_condition:
statement_2
3.2 Example
number = 0
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
Output: There is no output because both conditions are false. This example has no else block to handle the remaining case.
3.3 Using Multiple elif Statements
A conditional structure can contain multiple elif branches. Each branch checks a different condition.
day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
Output:
Wednesday
Python checks the conditions in order and executes the first matching branch. Since day == 3 is true, it prints Wednesday and skips the remaining conditions.
4. Understanding the else Statement
The else statement defines a default block that executes when none of the preceding if or elif conditions is true. The else branch does not have its own condition.
4.1 Syntax of else
if first_condition:
statement_1
elif second_condition:
statement_2
else:
default_statement
4.2 Example
number = -5
if number > 0:
print("Positive number")
elif number == 0:
print("Zero")
else:
print("Negative number")
Output:
Negative number
The first two conditions are false, so Python executes the else block.
4.3 Is else Mandatory?
No. An else branch is optional. Use it when the program needs a default action for all cases not covered by the preceding conditions. Without else, Python simply continues if none of the conditions matches.
5. Complete Syntax of if-elif-else
The general structure is:
if condition_1:
# Runs if condition_1 is True
statement_1
elif condition_2:
# Runs if condition_1 is False
# and condition_2 is True
statement_2
elif condition_3:
# Runs if all previous conditions are False
# and condition_3 is True
statement_3
else:
# Runs if all previous conditions are False
default_statement
5.1 Rules to Remember
- An
if statement is required at the beginning.
- There can be zero or more
elif branches.
- There can be at most one
else branch in a single if-elif-else chain.
- The
else branch, when present, must appear last.
- Conditions are checked from top to bottom.
- Only the first branch whose condition is true is executed.
- Each condition line ends with a colon.
- All statements belonging to the same block must use consistent indentation.
6. How if-elif-else Executes Step by Step
Python evaluates a conditional chain in a specific order. Understanding that order helps prevent incorrect results.
- Python evaluates the condition after
if.
- If it is true, Python executes the corresponding block and skips the rest of the chain.
- If it is false, Python evaluates the first
elif condition, if one exists.
- Python continues checking each
elif condition in order until one is true.
- If a condition is true, its block executes and the remaining branches are skipped.
- If all conditions are false and an
else block exists, Python executes that block.
- Execution then continues with the statement after the entire conditional structure.
6.1 Example with Trace
marks = 76
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Grade D")
Output:
Grade B
| Step |
Condition |
Result |
Action |
| 1 |
marks >= 90 |
False |
Check the next branch. |
| 2 |
marks >= 75 |
True |
Print Grade B. |
| 3 |
marks >= 60 |
Not evaluated |
Skipped. |
| 4 |
else |
Not reached |
Skipped. |
7. Using Comparison Operators in Conditions
Comparison operators are frequently used to create conditions. They compare two values and return a Boolean result: True or False.
| Operator |
Meaning |
Example |
Result |
== |
Equal to |
5 == 5 |
True |
!= |
Not equal to |
5 != 3 |
True |
> |
Greater than |
8 > 4 |
True |
< |
Less than |
2 < 7 |
True |
>= |
Greater than or equal to |
10 >= 10 |
True |
<= |
Less than or equal to |
4 <= 6 |
True |
7.1 Example: Comparing Prices
price = 1200
if price < 500:
print("Budget product")
elif price <= 1000:
print("Mid-range product")
else:
print("Premium product")
Output:
Premium product
The price is neither below 500 nor at most 1000, so the else branch executes.
8. Practical Example: Student Grading System
A grading system is a common application of conditional statements. The program compares marks with grade boundaries and assigns a grade.
marks = 84
if marks < 0 or marks > 100:
print("Invalid marks")
elif marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
elif marks >= 40:
print("Grade E")
else:
print("Fail")
Output:
Grade B
8.1 Explanation
- The first condition rejects marks outside the range of 0 to 100.
- The next condition checks whether marks are at least 90.
- If not, Python checks whether marks are at least 80, then 70, 60, and 40.
- If none of the passing grade conditions is true, the student receives a fail result.
Important: The order of grade conditions matters. Checking marks >= 40 before marks >= 90 would cause a mark of 95 to match the first passing condition and receive the wrong grade.
9. Practical Example: Checking Age Categories
This example categorizes a person based on age.
age = 25
if age < 0:
print("Invalid age")
elif age <= 12:
print("Child")
elif age <= 19:
print("Teenager")
elif age <= 59:
print("Adult")
else:
print("Senior")
Output:
Adult
The program first checks invalid negative values. It then tests age ranges from the youngest category to the oldest. Since the age is 25, the adult branch is selected.
10. Practical Example: Discount Calculator
Businesses often use conditional statements to determine discounts based on the total purchase amount.
amount = 6500
if amount < 0:
print("Invalid purchase amount")
elif amount >= 10000:
discount = amount * 0.20
print("Discount:", discount)
elif amount >= 5000:
discount = amount * 0.10
print("Discount:", discount)
elif amount >= 2000:
discount = amount * 0.05
print("Discount:", discount)
else:
discount = 0
print("No discount")
final_amount = amount - discount
print("Final amount:", final_amount)
Output:
Discount: 650.0
Final amount: 5850.0
Because the purchase amount is 6500, it qualifies for a 10% discount. The program calculates the discount and subtracts it from the original amount.
11. Combining if-elif-else with Logical Operators
Logical operators help combine multiple conditions into one decision. Python provides and, or, and not.
| Operator |
Purpose |
Example |
and |
True when both conditions are true. |
age >= 18 and has_id |
or |
True when at least one condition is true. |
is_student or is_senior |
not |
Reverses a Boolean result. |
not is_blocked |
11.1 Example: Login Eligibility
username = "admin"
password_correct = True
account_active = True
if username == "admin" and password_correct and account_active:
print("Access granted")
elif username == "admin" and not account_active:
print("Account is inactive")
else:
print("Access denied")
Output:
Access granted
The first branch requires all three conditions to be true. In real applications, passwords should be securely verified rather than stored or compared as plain text.
12. Taking User Input for Conditional Decisions
Python's input() function lets users enter values at runtime. The function returns text, so numeric input must usually be converted to an integer or floating-point number before numerical comparisons.
12.1 Example: Checking a Number
try:
number = int(input("Enter a number: "))
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else:
print("Zero")
except ValueError:
print("Please enter a valid whole number.")
Sample run:
Enter a number: -8
Negative number
The try-except block handles input that cannot be converted into an integer. Without this handling, entering text such as hello would cause a ValueError.
12.2 Example: Simple Calculator Menu
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Choose an operation: ")
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if choice == "1":
print("Result:", a + b)
elif choice == "2":
print("Result:", a - b)
elif choice == "3":
print("Result:", a * b)
elif choice == "4":
if b == 0:
print("Cannot divide by zero")
else:
print("Result:", a / b)
else:
print("Invalid choice")
except ValueError:
print("Please enter valid numbers.")
This example uses an if-elif-else chain to choose an operation and a nested if statement to prevent division by zero.
13. Nested if Statements Versus if-elif-else
A nested if statement is an if statement placed inside another conditional block. Use nesting when one decision depends on another decision. Use an if-elif-else chain when choosing among alternatives at the same decision level.
13.1 Nested if Example
age = 22
has_license = True
if age >= 18:
if has_license:
print("Allowed to drive")
else:
print("A driving license is required")
else:
print("Not old enough to drive")
Output:
Allowed to drive
13.2 Comparison
| Feature |
if-elif-else |
Nested if |
| Purpose |
Selects among alternative conditions. |
Checks a condition inside another condition. |
| Structure |
Branches are aligned at the same indentation level. |
Inner statements are indented inside an outer block. |
| Best use |
Grades, categories, menu choices. |
Multi-step eligibility checks. |
| Readability |
Usually simpler for mutually exclusive alternatives. |
Can become difficult to read when deeply nested. |
14. Common Mistakes When Implementing if-elif-else
14.1 Using Assignment Instead of Comparison
Incorrect:
number = 10
if number = 10:
print("Ten")
This causes a syntax error because = assigns a value, while == compares values.
Correct:
number = 10
if number == 10:
print("Ten")
14.2 Incorrect Indentation
Incorrect:
age = 20
if age >= 18:
print("Adult")
Correct:
age = 20
if age >= 18:
print("Adult")
Python uses indentation to identify blocks. Four spaces per indentation level is the common convention.
14.3 Incorrect Condition Order
Incorrect:
marks = 95
if marks >= 40:
print("Pass")
elif marks >= 90:
print("Excellent")
Output:
Pass
The first condition is already true, so the second branch is never reached.
Correct:
marks = 95
if marks >= 90:
print("Excellent")
elif marks >= 40:
print("Pass")
else:
print("Fail")
14.4 Forgetting the Colon
Incorrect:
if age >= 18
print("Adult")
Correct:
if age >= 18:
print("Adult")
14.5 Using Separate if Statements Instead of elif
Separate if statements are evaluated independently. An if-elif-else chain stops after its first true branch.
score = 85
if score >= 60:
print("Passed")
if score >= 80:
print("Good score")
Output:
Passed
Good score
Both conditions are checked, so both messages appear. If the requirements call for only one result, use an if-elif-else chain instead.
14.6 Comparing Values of Different Types
Values returned by input() are strings. Comparing numeric input without conversion can produce unexpected logic or a TypeError.
Incorrect:
age = input("Enter your age: ")
if age >= 18:
print("Adult")
Correct:
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
For robust programs, also handle invalid input with try-except.
15. Best Practices for Writing Conditional Statements
- Write conditions in a clear, readable order.
- Place more specific or higher-priority conditions before broader conditions when the logic requires it.
- Use
elif for alternatives that should be mutually exclusive.
- Use
else to handle the remaining cases when appropriate.
- Keep indentation consistent, preferably four spaces per level.
- Use descriptive variable names such as
marks, age, and purchase_amount.
- Validate user input before performing calculations.
- Consider boundary values such as 0, 18, 40, 60, or the exact limits of a category.
- Avoid unnecessary nesting and overly complicated conditions.
- Test every branch, including the default branch and invalid inputs.
- Use parentheses in complex conditions when they improve readability.
- Ensure every branch matches the intended business rule.
16. Testing Conditional Logic
Testing verifies that each branch behaves as intended. For a grade calculator, test values around each boundary instead of checking only a typical score.
| Test input |
Expected category |
Reason |
| -1 |
Invalid marks |
Below the allowed range. |
| 0 |
Fail |
Valid score below 40. |
| 39 |
Fail |
Just below the passing mark. |
| 40 |
Grade E |
First passing boundary. |
| 79 |
Grade C |
Below the Grade B threshold. |
| 80 |
Grade B |
Grade B boundary. |
| 90 |
Grade A |
Grade A boundary. |
| 101 |
Invalid marks |
Above the allowed range. |
Boundary testing is especially important because a single operator such as > instead of >= can change the result at the exact threshold.
17. Mini Project: Electricity Bill Category
Create a program that categorizes electricity usage according to the number of units consumed. The following example uses illustrative thresholds; real electricity tariffs vary by location and provider.
try:
units = float(input("Enter electricity units consumed: "))
if units < 0:
print("Invalid units")
elif units <= 100:
print("Low usage")
elif units <= 300:
print("Medium usage")
elif units <= 500:
print("High usage")
else:
print("Very high usage")
except ValueError:
print("Please enter a valid numeric value.")
Sample run:
Enter electricity units consumed: 250
Medium usage
Project Explanation
- The program requests the number of units from the user.
- It converts the input into a floating-point number.
- Negative values are rejected.
- Valid values are categorized using an if-elif-else chain.
- Invalid numeric input is handled through
ValueError.
Suggested Improvements
- Calculate an estimated bill using clearly defined sample rates.
- Display the unit category and estimated amount.
- Add a fixed service charge if required by the sample rules.
- Test the exact boundaries of 100, 300, and 500 units.
18. Practice Exercises
- Write a program that checks whether an integer is positive, negative, or zero.
- Create a grading program that assigns a grade based on marks between 0 and 100.
- Write a program that categorizes a person's age as child, teenager, adult, or senior.
- Create a discount calculator that applies different discounts to different purchase totals.
- Write a program that identifies whether a number is divisible by 2, divisible by 3, or divisible by neither.
- Create a menu-driven calculator using an if-elif-else chain.
- Write a program that classifies temperatures as cold, moderate, warm, or hot.
- Build a simple login eligibility checker using username status and account activation.
18.1 Sample Exercise Solution: Even or Odd
number = int(input("Enter an integer: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
This example uses a simple if-else structure because there are only two possible outcomes.
19. Interview Questions and Answers
Q1. What is an if-elif-else statement in Python?
It is a conditional structure used to select one block of code from multiple alternatives based on conditions.
Q2. What does elif mean?
elif means “else if.” It checks another condition when the preceding conditions are false.
Q3. Is else compulsory in an if-elif-else structure?
No. The else branch is optional. Without it, the program continues normally if none of the conditions is true.
Q4. Can a conditional chain contain multiple elif statements?
Yes. A chain can contain multiple elif statements, allowing the program to check several alternatives.
Q5. Can there be multiple else statements in one if-elif-else chain?
No. A single if-elif-else chain can contain at most one else branch, and it must appear at the end.
Q6. What happens when two conditions could both be true?
In an if-elif-else chain, Python executes only the first branch whose condition evaluates to true. Later branches are skipped.
Q7. What is the difference between if and elif?
if starts the conditional chain. elif adds another condition that is considered only if all preceding conditions are false.
Q8. Why is the order of conditions important?
Python checks conditions from top to bottom. If a broad condition matches first, a more specific condition later in the chain may never execute.
Q9. What is the purpose of indentation?
Indentation identifies the statements belonging to each conditional block. Incorrect indentation can cause syntax errors or unintended program behavior.
Q10. What is the difference between multiple if statements and an if-elif-else chain?
Separate if statements are checked independently, so multiple blocks may execute. An if-elif-else chain executes at most one branch.
Q11. Can logical operators be used in conditions?
Yes. The and, or, and not operators combine or reverse logical conditions.
Q12. What happens if no condition is true and there is no else branch?
No block in that chain executes, and Python continues with the next statement after the chain.
20. Quick Revision Checklist
if checks the first condition.
elif checks additional conditions when previous ones are false.
else handles the remaining case if no earlier condition matches.
- Only the first true branch in a chain executes.
- Use a colon at the end of each condition line.
- Indent the statements inside each branch consistently.
- Use comparison operators such as
==, !=, >, and <=.
- Order conditions carefully to prevent unreachable branches.
- Convert numeric input before making numeric comparisons.
- Test boundary values and invalid input.
21. Conclusion
The if-elif-else structure is a fundamental Python feature for implementing decision-making logic. It allows a program to evaluate multiple conditions in order and execute the appropriate block. It is widely used in grading systems, discount calculators, input validation, menus, eligibility checks, and many other applications.
To use conditional statements effectively, understand how conditions are evaluated, choose the correct comparison operators, order branches carefully, maintain proper indentation, and test every important case. With regular practice, you can build clear, reliable, and maintainable Python programs.
Continue learning: Explore the Python Training Course or register for a course demo at JustAcademy.